#include "SDLEngine.h"

SDLEngine* SDLEngine::instance = nullptr;

SDLEngine::SDLEngine()
{}

SDLEngine::~SDLEngine()
{
	TTF_Quit();
	SDL_Quit();
}

void SDLEngine::Init()
{
	Init(800, 600);
}

void SDLEngine::Init(int width, int height)
{
	if(SDL_Init(SDL_INIT_EVERYTHING))
	{
		std::cout << SDL_GetError() << std::endl;
	}

	// Inisialise le Hasard.
	srand((unsigned)time(NULL));

	TTF_Init();
	SDLAudio::GetInstance ()->Init();
	SDLRenderer::GetInstance()->SetResolution(width, height);
}

void SDLEngine::Start()
{
	SDL_Event event;
	isRunning = true;

	std::vector<SDLComponent*>::iterator iter;
	for(iter = allComponents.begin(); iter != allComponents.end(); iter++)
	{
		(*iter)->Start();
	}

	while(isRunning)
	{
		SDLTimer::GetInstance()->Tick();

		while(SDL_PollEvent(&event))
		{
			SDLInput::GetInstance()->Poll(event);

			switch(event.type)
			{
			case SDL_QUIT:
				isRunning = false;
				break;
			case SDL_KEYDOWN:
				switch(event.key.keysym.sym)
				{
				case SDLK_ESCAPE:
					isRunning = false;
					break;
				default:
					break;
				}
			default:
				break;
			}	
		}
		Update();
		Draw();
	}
	Stop();
}

void SDLEngine::Stop()
{
	std::vector<SDLComponent*>::iterator iter;
	for(iter = allComponents.begin(); iter != allComponents.end(); iter++)
	{
		(*iter)->Stop();
	}

	SDLAudio::GetInstance()->StopMusic();
	SDLAudio::Kill();
	SDLResources::Kill();
	SDLTimer::Kill();
	SDLEngine::Kill();
}

void SDLEngine::Update()
{
	std::vector<SDLComponent*>::iterator iter;
	for(iter = allComponents.begin(); iter != allComponents.end(); iter++)
	{
		(*iter)->Update();
	}
}

void SDLEngine::Draw()
{
	SDLRenderer::GetInstance()->Clear();

	std::vector<SDLComponent*>::iterator iter;
	for(iter = allComponents.begin(); iter != allComponents.end(); iter++)
	{
		(*iter)->Draw();
	}

	SDLRenderer::GetInstance()->Present();
}




